package com.zhugang.week13.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program algorithms
 * @description: preorderTraversal
 * @author: chanzhugang
 * @create: 2022/09/13 13:16
 */
public class PreorderTraversal {

    /**
     * 144 二叉树的前序遍历
     * https://leetcode.cn/problems/binary-tree-preorder-traversal/
     *
     * @param root
     * @return
     */
    List<Integer> result = new ArrayList<>();

    public List<Integer> preorderTraversal(TreeNode root) {
        // 递归写法
        if (root == null) {
            return result;
        }
        result.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return result;
    }

    public List<Integer> preorderTraversal2(TreeNode root) {
        /**
         * 脑子想下压栈过程，画个图更好理解
         * 非递归：每个节点会在栈顶出现3次，定义3种状态
         */
        if (root == null) return result;
        Stack<SFrame> stack = new Stack<>();
        stack.push(new SFrame(1, root));
        while (!stack.isEmpty()) {
            if (stack.peek().status == 1) {
                result.add(stack.peek().node.val);
                // 修改状态机
                stack.peek().status = 2;
                if (stack.peek().node.left != null) {
                    // 要扩展左子树 左子节点压栈
                    stack.push(new SFrame(1, stack.peek().node.left));
                }
                continue;
            }
            if (stack.peek().status == 2) {
                stack.peek().status = 3;
                if (stack.peek().node.right != null) {
                    // 要扩展右子树 右子节点压栈
                    stack.push(new SFrame(1, stack.peek().node.right));
                }
                continue;
            }
            if (stack.peek().status == 3) {
                // 左右子树扩展完，出栈
                stack.pop();
            }
        }
        return result;
    }

    public class SFrame {
        int status;
        TreeNode node;

        public SFrame(int status, TreeNode node) {
            this.status = status;
            this.node = node;
        }
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}